#!/usr/bin/env python3

import time

BASE_YEAR = 1970

def getBaseDay(timestamp=None):
    timestamp = time.time() if timestamp == None else timestamp
    return int((timestamp / 60 / 60 + 8) // 24)

def isYear(year):
    return 1 if year % 4 == 0 and year % 100 != 0 or year % 400 == 0 else 0

def countYearDays(ey, sy=BASE_YEAR):
    days = 0

    while (sy < ey):
        days += 365 + isYear(sy)
        sy += 1

    return days


def getYear(timestamp=None):
    days = getBaseDay(timestamp)
    year = BASE_YEAR

    while days >= 365 + isYear(year):
        days -= 365 + isYear(year)
        year += 1

    return year

def getMonth(year=None, timestamp=None):
    year = getYear(timestamp) if year == None else year
    days = getBaseDay(timestamp) - countYearDays(year)
    month = 1
    MONTH = [[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
             [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]][isYear(year)]

    while days >= MONTH[month - 1]:
        days -= MONTH[month - 1]
        month += 1

    return month

def countMonthDays(month, year=getYear()):
    MONTH = [[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
             [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]][isYear(year)]
    days = 0

    while month > 1:
        days += MONTH[month - 1]
        month -= 1

    return days

def getDay(year=None, month=None, timestamp=None):
    year = getYear(timestamp) if year == None else year
    month = getMonth(timestamp) if month == None else month
    return getBaseDay(timestamp) - countYearDays(year) - countMonthDays(month, year)

def getHour(timestamp=None):
    timestamp = time.time() if timestamp == None else timestamp
    return int(timestamp / 60 / 60 + 8) - getBaseDay(timestamp) * 24

def getMin(timestamp=None):
    timestamp = time.time() if timestamp == None else timestamp
    return int(timestamp % 3600 / 60)

def ctime(timestamp=None):
    timestamp = time.time() if timestamp == None else timestamp
    year = getYear(timestamp)
    month = getMonth(year, timestamp)
    day = getDay(year, month, timestamp)
    hour = getHour(timestamp)
    minte = getMin(timestamp)

    return "%4d-%02d-%02d %02d:%02d" % (year, month, day, hour, minte)


if __name__ == '__main__':
    print(countMonthDays(3, 2017))
    print(getYear(), getMonth(), getDay(), getHour(), getMin())


